cmake_minimum_required(VERSION 3.0.0)

project(${CMAKE_PROJECT_NAME})

set(DATE	${CMAKE_DATE})
set(TIME	${CMAKE_TIME})
set(YEAR	${CMAKE_YEAR})
set(MONTH	${CMAKE_MONTH})
set(DAY		${CMAKE_DAY})
set(PROTOCOL_TYPE		${CMAKE_PROTOCOL_TYPE})

execute_process(
  COMMAND git describe --always --tags
  OUTPUT_VARIABLE git_tag
  OUTPUT_STRIP_TRAILING_WHITESPACE
  WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
)

message(STATUS "FIRMWARE VERSION: ${CMAKE_PROJECT_NAME}_V${git_tag}_${DATE}")

configure_file(
  "${PROJECT_SOURCE_DIR}/App/Version.h.in"
  "${PROJECT_SOURCE_DIR}/App/Version.h"
)

set(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "")
set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS "")

include(Toolchain-arm-none-eabi.cmake)

add_definitions(
	-std=c99
	-O2
	-DHSE_VALUE=8000000
	-DARM_MATH_CM0
	-ffunction-sections
	-Wl,-gc-sections
	-g
  -D${CMAKE_MCU_NAME}
)

if(CMAKE_BUILD_TYPE STREQUAL Debug)
  message("This is a Debug build")
  add_definitions(-DDebug)
endif()

if(CMAKE_BOOT_TYPE STREQUAL BOOT)
  add_definitions(-DBOOT)
endif()

set(FLAGS "-mthumb -mcpu=cortex-m0")
set(CMAKE_C_FLAGS	${FLAGS})
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-Map,${CMAKE_PROJECT_NAME}.map -mthumb -mcpu=cortex-m0 -specs=nano.specs -T ${CMAKE_SOURCE_DIR}/StartUp/stm32_flash.ld")

include_directories(
	.
	arm
	StartUp
	StdLib/inc
	App
)

add_executable(
	${CMAKE_PROJECT_NAME}.elf

	StartUp/system_stm32f0xx.c
	StartUp/startup_stm32f0xx.s

	StdLib/src/stm32f0xx_adc.c
	StdLib/src/stm32f0xx_dac.c
	StdLib/src/stm32f0xx_dma.c
	StdLib/src/stm32f0xx_exti.c
	StdLib/src/stm32f0xx_flash.c
	StdLib/src/stm32f0xx_gpio.c
	StdLib/src/stm32f0xx_misc.c
	StdLib/src/stm32f0xx_rcc.c
	StdLib/src/stm32f0xx_spi.c
	StdLib/src/stm32f0xx_syscfg.c
	StdLib/src/stm32f0xx_tim.c
	StdLib/src/stm32f0xx_usart.c

	App/CC2500.c
	App/Driver_Adc.c
	App/Driver_Button.c
	App/Driver_Delay.c
	App/Driver_Flash.c
	App/Driver_Interrupt.c
	App/Driver_Led.c
	App/Driver_Output.c
	App/Driver_Spi.c
	App/Driver_Uart.c
	App/Main.c
	App/Protocol.c
	App/Parameter.c
	App/Frsky_D16.c
)

target_link_libraries(
  ${CMAKE_PROJECT_NAME}.elf
  m
  c
  gcc
  rdimon
  nosys
)

set_property(
  SOURCE StartUp/startup_stm32f0xx.s
  PROPERTY LANGUAGE C
)

add_custom_target(
  ${CMAKE_PROJECT_NAME} ALL
  COMMAND ${OBJCOPY} -O binary	${CMAKE_PROJECT_NAME}.elf ${CMAKE_PROJECT_NAME}_${DATE}_V${git_tag}.bin
  COMMAND ${OBJCOPY} -O ihex		${CMAKE_PROJECT_NAME}.elf ${CMAKE_PROJECT_NAME}_${DATE}_V${git_tag}.hex
  COMMAND ${OBJCOPY} -O binary	${CMAKE_PROJECT_NAME}.elf ${CMAKE_PROJECT_NAME}.bin
  COMMAND ${OBJCOPY} -O ihex		${CMAKE_PROJECT_NAME}.elf ${CMAKE_PROJECT_NAME}.hex
  DEPENDS ${CMAKE_PROJECT_NAME}.elf
)
